package io.renren.modules.job.task;

import io.renren.common.utils.DateUtils;
import io.renren.modules.sys.config.SysBottomOpening;
import io.renren.modules.sys.entity.SysBottomEntity;
import io.renren.modules.sys.service.SysBottomService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动创建下注活动
 *
 * @author wuxianji
 * @since 2017/11/14 上午6:56
 **/
@Component("creatBottomTask")
public class CreatBottomTask {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private String taskOpen = "OPEN";

    /**
     * 短局持续时间，单位分钟
     */
    private int shortMinus = 5;

    /**
     * 长局持续时间，单位分钟
     */
    private int longMinus = 10;

    @Autowired
    private SysBottomOpening sysBottomOpening;

    @Autowired
    private SysBottomService sysBottomService;

    public void create(String status) {
        logger.info("开盘状态为:{}", status);
        if (!StringUtils.equals(status, taskOpen)) {
            logger.info("status不是开启状态，暂停开盘");
            return;
        }
        doCreate();
    }

    private void doCreate() {

        String currentMinus = getCurrentMinus();
        if (sysBottomOpening.getShortOpening().containsKey(currentMinus)) {
            createNewBottom(sysBottomOpening.getShortOpening().get(currentMinus), shortMinus);
        }
        if (sysBottomOpening.getLongOpening().containsKey(currentMinus)) {
            createNewBottom(sysBottomOpening.getLongOpening().get(currentMinus), longMinus);
        }
    }

    /**
     * 创建新的下注
     * @param period 期数
     * @param duration 结束时间
     */
    private void createNewBottom(String period, Integer duration) {

        SysBottomEntity sysBottomEntity = new SysBottomEntity();
        sysBottomEntity.setBottomName(getCurrentDate() + period);
        sysBottomEntity.setDuration(duration);

        sysBottomService.save(sysBottomEntity);
    }

    /**
     * 获取当前时间，例：13：09
     * @return
     */
    private String getCurrentMinus() {
        return DateUtils.format(new Date(), "HHmm");
    }

    /**
     * 获取当前日期,例：20171118
     * @return
     */
    private String getCurrentDate() {
        return DateUtils.format(new Date(), "yyyyMMdd");
    }

    public static void main(String[] args) {
        CreatBottomTask creatBottomTask = new CreatBottomTask();
        System.err.println("result" + creatBottomTask.getCurrentMinus());
    }
}
